<template>
  <div>
    <!-- 租赁合同信息 -->
    <div class="card-wrap flex-column justify-end card-padding">
      <el-form :model="form" ref="carReplacementService" label-width="120px" :rules="type == 'detail' ? {} : rules" :label-position="type == 'detail' ? 'right' : 'top'">
        <div class="card-title-wrap">
          <span :style="{ fontWeight: type == 'detail' ? 'normal' : 'bold' }">替车信息</span>
          <span></span>
        </div>
        <!-- 租赁合同信息 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="替车分类:" prop="replacementCarType">
              <el-select style="width: 80%" v-if="type !== 'detail'" v-model="form.replacementCarType" clearable>
                <template v-for="dict in typeList">
                  <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </template>
              </el-select>
              <dict-tag v-if="type == 'detail'" :options="dict.type.car_sorting" :value="form.replacementCarType" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="替车时间:" prop="replacementTime">
              <div style="display: flex; justify-content: start; align-items: center" v-if="type !== 'detail'">
                <div style="width: 70%">
                  <el-date-picker
                    style="width: 100%"
                    @change="changeTime"
                    v-model="form.replacementTime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  >
                  </el-date-picker>
                </div>
                <span style="margin-left: 20px">{{ form.dataDay }} 天{{ form.Hour }} 小时</span>
              </div>
              <div v-if="type == 'detail'">
                <span>{{ form.replacementCarStartTime | filterNull }} 至 {{ form.replacementCarEndTime | filterNull }}</span>
                <span style="margin-left: 20px">{{ form.dataDay | filterNull }} 天{{ form.Hour | filterNull }} 小时</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="司机与否:" prop="isDriver">
              <el-select style="width: 80%" v-if="type !== 'detail'" v-model="form.isDriver" clearable>
                <template v-for="dict in dict.type.sys_yes_no">
                  <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </template>
              </el-select>
              <span v-if="type == 'detail'">{{ form.isDriver == 'Y' ? '是' : form.isDriver == 'N' ? '否' : '' | filterNull }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8" v-if="form.isDriver == 'Y'">
            <el-form-item label="选择司机:" prop="driverName">
              <el-input v-if="type !== 'detail'" readonly style="width: 80%" v-model="form.driverName" @click.native="changeDriver"></el-input>
              <span v-if="type == 'detail'">{{ form.driverName | filterNull }}</span>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8" v-if="form.replacementCarType == 4">
            <el-form-item label="事故责任:" prop="eeeee">
              <el-select style="width: 80%" v-if="type !== 'detail'" v-model="form.eeeee" clearable>
                <template v-for="dict in dict.type.accident_liability">
                  <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </template>
              </el-select>
              <span v-if="type == 'detail'">123</span>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="替车车牌号:" prop="replacementCarNo">
              <el-input v-if="type !== 'detail'" readonly style="width: 80%" v-model="form.replacementCarNo" @click.native="changeSelect"></el-input>
              <span v-if="type == 'detail'">{{ form.replacementCarNo | filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.replacementCarType == 5">
            <el-form-item label="是否有替车共用:" prop="isReplacementPublicCarNo">
              <!-- @change="changeComm" -->
              <el-select style="width: 80%" v-if="type !== 'detail'" v-model="form.isReplacementPublicCarNo" clearable>
                <template v-for="dict in dict.type.sys_yes_no">
                  <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </template>
              </el-select>
              <span v-if="type == 'detail'">{{ form.isReplacementPublicCarNo == 'Y' ? '是' : form.isReplacementPublicCarNo == 'N' ? '否' : '' | filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="16" v-if="form.replacementCarType == 5 && form.isReplacementPublicCarNo == 'Y'">
            <el-form-item label="替车共用车牌号:" prop="replacementPublicOrderIds">
              <el-select @change="changeName" multiple filterable style="width: 80%" v-if="type !== 'detail'" v-model="form.replacementPublicOrderIds" clearable>
                <template v-for="dict in commonList">
                  <el-option :label="dict.carPlateNo" :value="dict.orderCarId" :key="dict.orderCarId"></el-option>
                </template>
              </el-select>
              <span v-if="type == 'detail'">{{ form.replacementPublicCarNo | filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="备注:" prop="replacementCarRemark">
              <el-input v-if="type !== 'detail'" type="textarea" v-model="form.replacementCarRemark" maxlength="500" :rows="5" show-word-limit></el-input>
              <span v-if="type == 'detail'">{{ form.replacementCarRemark | filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="替车协议:" prop="replacementCarAgreementOssId">
              <ImageCommon v-model="form.replacementCarAgreementOssId" :disabled="type == 'detail'" :fileSize="10" :limit="20" :upType="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 添加或修改测试单表对话框----选择司机 -->
    <el-dialog title="司机列表" :visible.sync="open" append-to-body class="form-dialog" width="70%">
      <SearchContent :queryParams="queryParamsDig" @query="handleQueryDig" @reset="resetQueryDig">
        <el-col :span="6">
          <el-form-item label="司机姓名:" prop="driverName">
            <el-input style="width: 100%" v-model="queryParamsDig.driverName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属公司:" prop="belongCompanyId">
            <!-- <el-input style="width: 100%" v-model="queryParamsDig.belongCompanyId"></el-input> -->
            <el-select v-model="queryParamsDig.belongCompanyId" placeholder="请选择公司" clearable>
              <el-option v-for="item in deptList.company" :label="item.deptName" :value="item.deptId" :key="item.deptId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话:" prop="driverPhone">
            <el-input style="width: 100%" v-model="queryParamsDig.driverPhone" maxlength="11" @input="queryParamsDig.driverPhone = queryParamsDig.driverPhone.replace(/^0|[^0-9]/g, '')"></el-input>
          </el-form-item>
        </el-col>
      </SearchContent>
      <el-row>
        <table-page :loading="loading" :dataList="dataList" border :total="total" :page.sync="queryParamsDig.pageNum" :limit.sync="queryParamsDig.pageSize" @setSizeCurrent="getList">
          <!-- 操作插槽 -->
          <template slot="tableColAc">
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="text" @click="selectGys(scope.row)">选择司机</el-button>
              </template>
            </el-table-column>
          </template>
          <!-- 普通列插槽 -->
          <template slot="tableCol">
            <el-table-column label="司机编码" align="center" prop="driverCode" min-width="140px" show-overflow-tooltip />
            <el-table-column label="司机姓名" align="center" prop="driverName" min-width="140px" show-overflow-tooltip />
            <el-table-column label="所属公司" align="center" prop="belongCompanyName" min-width="140px" show-overflow-tooltip />
            <el-table-column label="联系电话" align="center" prop="driverPhone" min-width="140px" show-overflow-tooltip />
            <el-table-column label="所在城市" align="center" prop="cityName" min-width="140px" show-overflow-tooltip />
          </template>
        </table-page>
      </el-row>
    </el-dialog>
    <!-- 添加或修改测试单表对话框----车辆列表 -->
    <el-dialog title="车辆列表" :visible.sync="openCl" append-to-body class="form-dialog" width="70%">
      <SearchContent :queryParams="queryParamsDigCl" @query="handleQueryDigCl" @reset="resetQueryDigCl">
        <el-col :span="6">
          <el-form-item label="品牌:" prop="brandName">
            <el-input style="width: 100%" v-model="queryParamsDigCl.brandName"></el-input>
            <!-- <el-select v-model="queryParamsDigCl.driverName" clearable filterable style="width: 100%" @change="getSeriesName">
              <template v-for="dict in brandList">
                <el-option :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
              </template>
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车系:" prop="seriesName">
            <el-input style="width: 100%" v-model="queryParamsDigCl.seriesName"></el-input>
            <!-- <el-select v-model="queryParamsDigCl.b" clearable filterable style="width: 100%" @change="getModelName">
              <template v-for="dict in seriesList">
                <el-option :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
              </template>
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车型:" prop="modelName">
            <el-input style="width: 100%" v-model="queryParamsDigCl.modelName"></el-input>
            <!-- <el-select v-model="queryParamsDigCl.c" filterable style="width: 100%" clearable>
              <template v-for="dict in carIdList">
                <el-option :label="dict.name" :value="dict.id" :key="dict.id"></el-option>
              </template>
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车牌号:" prop="carNo">
            <el-input style="width: 100%" v-model="queryParamsDigCl.carNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆归属:" prop="ascription">
            <el-input style="width: 100%" v-model="queryParamsDigCl.ascription"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆产权:" prop="propertyRight">
            <el-input style="width: 100%" v-model="queryParamsDigCl.propertyRight"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆运营:" prop="operationsName">
            <el-input style="width: 100%" v-model="queryParamsDigCl.operationsName"></el-input>
          </el-form-item>
        </el-col>
      </SearchContent>
      <el-row>
        <table-page :loading="loadingCl" :dataList="dataListCl" border :total="totalCl" :page.sync="queryParamsDigCl.pageNum" :limit.sync="queryParamsDigCl.pageSize" @setSizeCurrent="getListCl">
          <!-- 操作插槽 -->
          <template slot="tableColAc">
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="text" @click="selectGysCl(scope.row)">选择车辆</el-button>
              </template>
            </el-table-column>
          </template>
          <!-- 普通列插槽 -->
          <template slot="tableCol">
            <el-table-column label="品牌" align="center" prop="brandName" min-width="100px" show-overflow-tooltip />
            <el-table-column label="车系" align="center" prop="seriesName" min-width="140px" show-overflow-tooltip />
            <el-table-column label="车型" align="center" prop="modelName" min-width="360px" show-overflow-tooltip />
            <el-table-column label="车牌号" align="center" prop="carNo" min-width="140px" show-overflow-tooltip />
            <el-table-column label="车辆产权" align="center" prop="propertyRightName" min-width="140px" show-overflow-tooltip />
            <el-table-column label="车辆归属" align="center" prop="ascription" min-width="140px" show-overflow-tooltip />
            <el-table-column label="车辆运营" align="center" prop="operationsName" min-width="140px" show-overflow-tooltip />
          </template>
        </table-page>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { queryDriverList, queryCarList, queryPublicLicensePlatesList, queryInsurancePackages } from '@/api/pickUpTheCar'
import SearchContent from '@/components/SearchContent/index.vue'
import { getBrandNames, getSeriesName, getModelName } from '@/api/system/linkageSelect.js'
import * as apis from '@/api/flowable/examine/list/api.js'
export default {
  name: 'carReplacementService',
  dicts: ['car_nature', 'sys_yes_no', 'accident_liability', 'car_sorting', 'car_sorting_wb', 'car_sorting_xx'],
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: '',
    },
  },
  components: {
    SearchContent,
  },
  computed: {
    form: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      },
    },
    typeList() {
      let arr = []
      if (this.$route.query.btnType == 1 || this.form.btnType == 1) {
        arr = this.dict.type.car_sorting
      } else if (this.$route.query.btnType == 2 || this.form.btnType == 2) {
        arr = this.dict.type.car_sorting.slice(0, 4)
      } else if (this.$route.query.btnType == 3 || this.form.btnType == 3) {
        arr = this.dict.type.car_sorting.slice(4, 5)
      } else if (this.$route.query.btnType == 4 || this.form.btnType == 4) {
        arr = this.dict.type.car_sorting.slice(0, 5)
      }
      return arr
    },
    type() {
      let status
      switch (this.state) {
        case 'write':
          status = 'edit'
          break
        case 'disabled':
          status = 'detail'
          break
        case 'readonly':
          status = 'detail'
          break
        case 'detail':
          status = 'detail'
          break
        case 'edit':
          status = 'edit'
        case 'add':
          status = 'add'
          break
      }
      return status
    },
  },
  data() {
    return {
      deptList: {
        company: [], //公司
        department: [], // 组织
      },
      commonList: [],
      brandList: [],
      seriesList: [],
      carIdList: [],
      dataList: [],
      loading: false,
      total: 0,
      queryParamsDig: {
        pageNum: 1,
        pageSize: 10,
      },
      open: false,
      dataListCl: [],
      loadingCl: false,
      totalCl: 0,
      queryParamsDigCl: {
        pageNum: 1,
        pageSize: 10,
      },
      openCl: false,
      rules: {
        replacementCarType: [
          {
            required: true,
            message: '请选择替车分类',
            trigger: 'change',
          },
        ],
        replacementTime: [
          {
            type: 'array',
            required: true,
            message: '请选择替车时间',
          },
        ],
        isDriver: [
          {
            required: true,
            message: '请选择司机与否',
            trigger: 'change',
          },
        ],
        driverName: [
          {
            required: true,
            message: '请选择司机',
            trigger: 'change',
          },
        ],
        // eeeee: [
        //   {
        //     required: true,
        //     message: '请选择事故责任',
        //     trigger: 'change',
        //   },
        // ],
        replacementCarNo: [
          {
            required: true,
            message: '请选择替车车牌号',
            trigger: 'change',
          },
        ],
        isReplacementPublicCarNo: [
          {
            required: true,
            message: '请选择是否有替车共用',
            trigger: 'change',
          },
        ],
        replacementPublicCarNo: [
          {
            required: true,
            message: '请选择替车共用车牌号',
            trigger: 'change',
          },
        ],
      },
    }
  },
  watch: {
    'form.replacementCarStartTime': {
      handler(val) {
        if (val && this.form.replacementCarEndTime) {
          this.changeCreateTime([val, this.form.replacementCarEndTime])
        } else {
          this.form.replacementTime = []
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    // this.getBrandNames()
    if (this.$route.query.orderId) {
      this.getDeptList(2)
      this.queryPublicLicensePlatesList()
    }
  },
  methods: {
    changeName() {
      const replacementPublicCarNo = this.form.replacementPublicOrderIds?.map((orderCarId) => {
        const match = this.commonList.find((item) => item.orderCarId === orderCarId)
        return match ? match.carPlateNo : null
      })
      // .join(',')
      console.log(replacementPublicCarNo, '-')
      this.$set(this.form, 'replacementPublicCarNo', replacementPublicCarNo.join(','))
    },
    //查询车辆信息和商业险信息
    async queryInsurancePackages(carId) {
      let params = {
        carId,
      }
      try {
        let res = await queryInsurancePackages(params)
        console.log(res.data, 'pppp')
        let { carBasic, insurancePackagesVoList } = res.data
        delete carBasic.customerName
        delete carBasic.contractStartTime
        delete carBasic.contractEndTime
        this.form = { ...this.form, ...carBasic, insurancePackages: insurancePackagesVoList }
      } catch (error) {}
    },
    // 公共车牌号
    changeComm() {
      console.log(this.form.isReplacementPublicCarNo)
      if (this.form.isReplacementPublicCarNo == 'Y') {
        this.queryPublicLicensePlatesList()
      }
    },
    async queryPublicLicensePlatesList() {
      let params = {
        orderId: this.$route.query.orderId,
      }
      try {
        let res = await queryPublicLicensePlatesList(params)
        this.commonList = res.data
      } catch (error) {}
    },
    getDeptList(deptType) {
      let params = {
        deptType,
      }
      apis.DeptList(params).then((res) => {
        if (res.code == 200) {
          switch (deptType) {
            case 1:
              this.deptList.department = res?.data ?? []
              break
            case 2:
              this.deptList.company = res?.data ?? []
              break
          }
        }
      })
    },
    // 获取品牌
    getBrandNames() {
      getBrandNames({ brandName: '' }).then((res) => {
        this.brandList = res
      })
    },
    // 获取车型
    getModelName() {
      if (this.queryParamsDigCl.b) {
        getModelName(this.queryParamsDigCl.b).then((res) => {
          this.carIdList = res
          this.$set(this.queryParamsDigCl, 'c', '')
        })
      } else {
        this.carIdList = []
        this.$set(this.queryParamsDigCl, 'c', '')
      }
    },
    // 获取车系
    getSeriesName() {
      if (this.queryParamsDigCl.driverName) {
        getSeriesName(this.queryParamsDigCl.driverName).then((res) => {
          this.seriesList = res
          this.$set(this.queryParamsDigCl, 'b', '')
          this.$set(this.queryParamsDigCl, 'c', '')
        })
      } else {
        this.seriesList = []
        this.carIdList = []
        this.$set(this.queryParamsDigCl, 'b', '')
        this.$set(this.queryParamsDigCl, 'c', '')
      }
    },
    selectGys(row) {
      this.open = false
      this.$set(this.form, 'driverName', row.driverName)
      this.$set(this.form, 'driverId', row.driverId)
    },
    selectGysCl(row) {
      this.openCl = false
      this.queryInsurancePackages(row.carId)
      this.$set(this.form, 'replacementCarNo', row.carNo)
    },
    resetQueryDig() {
      this.queryParamsDig = {
        pageNum: 1,
        pageSize: 10,
      }
      this.getList()
    },
    resetQueryDigCl() {
      this.queryParamsDigCl = {
        pageNum: 1,
        pageSize: 10,
      }
      this.getListCl()
    },
    handleQueryDig() {
      this.getList()
    },
    handleQueryDigCl() {
      this.getListCl()
    },
    /** 查询列表司机 */
    getList() {
      this.loading = true
      queryDriverList(this.queryParamsDig).then((res) => {
        if (res.code == '200') {
          const { rows, total } = res
          this.dataList = rows
          this.total = total
          this.loading = false
        }
      })
    },
    /** 查询列表 */
    getListCl() {
      this.loadingCl = true
      queryCarList(this.queryParamsDigCl).then((res) => {
        if (res.code == '200') {
          const { rows, total } = res
          this.dataListCl = rows
          this.totalCl = total
          this.loadingCl = false
        }
      })
    },
    // 选择司机
    changeDriver() {
      this.open = true
      this.queryParamsDig = {
        pageNum: 1,
        pageSize: 10,
      }
      this.getList()
    },
    // 选择车牌号带出其他信息
    changeSelect() {
      this.openCl = true
      this.queryParamsDigCl = {
        pageNum: 1,
        pageSize: 10,
      }
      this.getListCl()
    },
    // 创建时间发生改变
    changeCreateTime(val) {
      let time = this.calculateDifference(val[0], val[1])
      console.log(time, 'time')
      this.$set(this.form, 'dataDay', time.days ? time.days : 0)
      this.$set(this.form, 'Hour', time.hours == 'NaN' ? 0.0 : time.hours)
      this.$set(this.form, 'lease', time.upDays ? time.upDays : '')
    },
    // 创建时间发生改变
    changeTime(val) {
      this.form.replacementCarStartTime = val && val[0]
      this.form.replacementCarEndTime = val && val[1]
      let time = this.calculateDifference(this.form.replacementCarStartTime, this.form.replacementCarEndTime)
      this.$set(this.form, 'dataDay', time.days)
      this.$set(this.form, 'Hour', time.hours)
      this.$set(this.form, 'lease', time.upDays)
      let dataLast = new Date(this.form.replacementCarEndTime)
      let dataLastHt = new Date(this.form.contractEndTime)
      if (dataLast > dataLastHt) {
        this.$message.error('替车时间不能大于合同时间结束时间')
        this.form.replacementCarEndTime = ''
        this.form.dataDay = ''
        this.form.Hour = ''
        this.form.lease = ''
        this.form.replacementTime = []
      }
    },
    calculateDifference(replacementCarStartTime, replacementCarEndTime) {
      const startDate = new Date(replacementCarStartTime)
      const endDate = new Date(replacementCarEndTime)
      const diffInMs = endDate - startDate
      const msInHour = 1000 * 60 * 60
      const msInDay = msInHour * 24
      const days = Math.floor(diffInMs / msInDay)
      const hours = ((diffInMs % msInDay) / msInHour).toFixed(1)
      // 向上取整天数
      const upDays = Math.ceil(diffInMs / msInHour / 24)
      return {
        days: days,
        hours: hours,
        upDays: upDays,
      }
    },
    valid() {
      return new Promise(async (resolve) => {
        let result = true
        let refs = Object.values(this.$refs)
        for (let index = 0; index < refs?.length; index++) {
          const ref = refs[index]
          if (Object.prototype.toString.call(ref) == '[object Array]') {
            for (let i = 0; i < ref.length; i++) {
              const element = ref[i]
              if (element?.valid) {
                let rc = await element?.valid?.()
                result = result && rc
              }
              if (element?.validate) {
                let rf = await this._valid(ref)
                result = result && rf
              }
              if (element?.form_validate) {
                let rf = await this._valid(ref, 'form_validate')
                result = result && rf
              }
            }
          } else {
            if (ref?.valid) {
              let rc = await ref?.valid?.()
              result = result && rc
            }
            if (ref?.validate) {
              let rf = await this._valid(ref)
              result = result && rf
            }
            if (ref?.form_validate) {
              let rf = await this._valid(ref, 'form_validate')
              result = result && rf
            }
          }
        }
        resolve(result)
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.box-wraps:after {
  content: '';
  display: block;
  clear: both;
  width: 32%;
}
</style>
